package com.shigu.admin.manager.actions;


import com.opentae.data.mall.beans.RolePermission;
import com.shigu.admin.manager.common.PermissionListener;
import com.shigu.admin.manager.vo.Nav;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 主页面
 * Created by zhaohongbo on 16/5/10.
 */
@Controller
public class MainAction extends BaseAction{

    @Autowired
    private PermissionListener permissionListener;

    /**
     * 首页
     * @return
     */
    @RequestMapping("/index")
    public String mainPage(HttpSession session, Model model){
        model.addAttribute("userName", getUserName());
        model.addAttribute("loginName", getLoginName());
        return "index";
    }

    @RequestMapping("/nav")
    @ResponseBody
    public Set<Nav> navs() {
        Map<RolePermission, List<RolePermission>> permissions = getPermissions(null);
        Set<Nav> navs = new LinkedHashSet<>();
        for (Map.Entry<RolePermission, List<RolePermission>> entry : permissions.entrySet()) {
            RolePermission key = entry.getKey();
            Nav nav = packNav(key);
            nav.setIcon("fa-cubes");
            nav.setChildren(new LinkedHashSet<Nav>());
            navs.add(nav);
            List<RolePermission> value = entry.getValue();
            if (value.size()>0) {
                for (RolePermission permission : value) {
                    Nav navbar = packNav(permission);
                    navbar.setIcon("&#xe63c;");
                    navbar.setHref(permissionListener.getUrlByPermission(permission.getPermissionTag()));
                    nav.getChildren().add(navbar);
                }
            }else{
                nav.setHref(permissionListener.getUrlByPermission(key.getPermissionTag()));
            }
        }
        return navs;
    }

    private Nav packNav(RolePermission permission) {
        Nav nav = new Nav();
        nav.setTitle(permission.getPermissionComment());
        return nav;
    }

    @RequestMapping("/index/rightPanel")
    public String controlPanal() {
        return "common/rightPanel";
    }
}
